﻿using OnlineEducation.Data;
using OnlineEducation.Data.Entities;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace OnlineEducation.Extensions
{
    public static class DbContextExtensions
    {
        public static UserManager<ApplicationUser> UserManager { get; set; }
        public static RoleManager<ApplicationRole> RoleManager { get; set; }
        public static async Task EnsureSeeded(this ApplicationDbContext context)
        {
           

            if (await RoleManager.RoleExistsAsync("SuperAdmin") == false)
            {
                await RoleManager.CreateAsync(new ApplicationRole("SuperAdmin"));
            }

            if (await RoleManager.RoleExistsAsync("Teacher") == false)
            {
                await RoleManager.CreateAsync(new ApplicationRole("Teacher"));
            }

            if (await RoleManager.RoleExistsAsync("Student") == false)
            {
                await RoleManager.CreateAsync(new ApplicationRole("Student"));
            }

            if (await UserManager.FindByEmailAsync("admin") == null)
            {
                var user = new ApplicationUser
                {

                    UserName = "admin",
                    Email = "admin@xxx.com",
                    EmailConfirmed = true,
                    LockoutEnabled = false
                };

                await UserManager.CreateAsync(user, "Admin@1234");
            }

            var admin = await UserManager.FindByEmailAsync("admin@xxx.com");

            if (await UserManager.IsInRoleAsync(admin, "SuperAdmin") == false)
            {
                await UserManager.AddToRoleAsync(admin, "SuperAdmin");
            }

            if (File.Exists("./quartz_tables_mysql.sql"))
            {
                //create quartz table 
                string sql = File.ReadAllText("./quartz_tables_mysql.sql");

                using (var command = context.Database.GetDbConnection().CreateCommand())
                {
                    using (var connect = command.Connection)
                    {
                        connect.Open();
                        command.CommandText = sql;
                        command.CommandType = CommandType.Text;
                        command.ExecuteNonQuery();
                    }
                }
            }
            else
            {
                throw new Exception("cannot find the 'quartz_tables_mysql.sql' to initilize table schema of quartz.net.");
            }
        }

     
    }
}
